#pragma once
#include <iostream>
#include <string>
#include <sys/select.h>
#include "socket.hpp"
#include "InetAddr.hpp"

class SelectServer
{
private:
    const static int g_num = sizeof(fd_set) * 8;
    const static int g_default = -1;
private:
    std::shared_ptr<Socket> _sp;
    uint16_t _port;
    int fd_array[g_num];

public:
    SelectServer(uint16_t port)
        : _sp(std::make_unique<TcpSocket>()), _port(port)
    {
        _sp->buildListenSocket(_port);
    }
    ~SelectServer()
    {
    }
    void Init()
    {
        fd_array[0] = _sp->Sockfd();
        for (int i = 1; i < g_num; i++)
            fd_array[i] = g_default;
    }
    void Loop()
    {
        while (true)
        {
            sleep(1);
            // _sp->acceptSocket(); 不能，listensock && accept 我们把他看作是IO函数，只关心新连接的到来，等价于读事件就绪！
            fd_set fd_read;
            FD_ZERO(&fd_read);
            timeval timeout = {3, 0};
            int fd_max = g_default;
            for (int i = 0; i < g_num; i ++)
            {
                // 将合法的fd，添加到fd_read中
                if (fd_array[i] != g_default)
                {
                    FD_SET(fd_array[i], &fd_read);
                }
                // 寻找最大的fd
                fd_max = std::max(fd_max, fd_array[i]);
            }
            int n = ::select(fd_max + 1, &fd_read, nullptr, nullptr, /*&timeout*/nullptr);
            switch (n)
            {
            case 0:
                LOG(DEBUG, "time out, %d.%d\n", timeout.tv_sec, timeout.tv_usec);
                break;
            case -1:
                LOG(ERROR, "select error\n");
                break;
            default:
                LOG(INFO, "have event ready, n : %d\n", n);
                HandlerTask(fd_read);
                break;
            }
        }
    }
    void HandlerTask(const fd_set &fd_read)
    {
        // 事件派发
        for (int i = 0; i < g_num; i ++ )
        {
            // 是否是合法的？
            if(fd_array[i] == g_default) continue;
            // 是否是就绪的?
            if (FD_ISSET(fd_array[i], &fd_read))
            {
                // 是listen sockfd还是普通fd
                if (fd_array[i] == _sp->Sockfd())
                {
                    // listen sockfd
                    Accept();
                }
                else 
                {
                    // normal sockfd
                    HandlerIO(i);
                }
            }
        }
    }
    void Accept()
    {
        InetAddr addr;
        int sockfd = _sp->acceptSocket(&addr);

        if (sockfd > 0)
        {
            // 将文件描述符添加进fd_array
            bool flag = false;
            for (int i = 0; i < g_num; i++)
            {
                if (fd_array[i] == g_default)
                {
                    fd_array[i] = sockfd;
                    flag = true;
                    LOG(DEBUG, "add %d to fd_array success!\n", sockfd);
                    break;
                }
            }
            if (!flag)
            {
                LOG(WARNING, "Server Is Full!\n");
                ::close(sockfd);
            }
        }
        else
        {
            std::cout << "accept error" << std::endl;
            perror("accept");
        }
    }
    void HandlerIO(int fdi)
    {
        char buffer[1024] = {0};
        int n = recv(fd_array[fdi], buffer, sizeof(buffer) - 1, 0);
        buffer[n] = 0;
        if (n > 0)
        {
            std::string echo = "echo #";
            echo += buffer;
            std::cout << echo << std::endl;
        }
        else if (n == 0)
        {
            close(fd_array[fdi]);
            fd_array[fdi] = g_default;
            LOG(DEBUG, "recv end");
        }
        else 
        {
            close(fd_array[fdi]);
            fd_array[fdi] = g_default;
            LOG(ERROR, "recv error");
        }
    }
};